<template>

	<div class="map">

		<div id="mapComponent" ref="mapComponent"></div>
	</div>
</template>

<script>
	export default {
		name: 'mapComponent',
		data() {
			return {
				lushu: '',
				nowLoction: '',
				carinfo: '',
				distance: '',
				paytime: '',
			}
		},
		watch: {
			lushu: function(val) {
				val.start();
				val.showInfoWindow();
			},
			nowLoction: {
				handler: function(val) {
					if (val != '') {
						let a = JSON.parse(val);
						this.postCarLoc(a);

					}
				}
			},
			driving: {
				handler: function(val) {
					for (let i in val) {
						let r = parseInt(Math.random() * 255);
						let g = parseInt(Math.random() * 255);
						let b = parseInt(Math.random() * 255);
						let c = `rgb(${r},${g},${b})`
						let w = Math.random() * 2 + 3
						this.pilyLine(val[i][0], val[i][1], 'red');
						this.pilyLine(val[i][1], val[i][2], c, w);
					}
				},
				deep: true
			}
		},
		mounted() {
			this.map()
		},
		/*
			cars: 全部车辆信息
			driving：全部行驶信息
			gongneng：1 用户行驶信息路书
					  2 车辆停止位置
					  3 全体车辆位置
					  4 公交车辆路线查看
		*/
		props: ['gongneng', 'loc', 'info', 'speed', 'address', 'cars', 'driving', 'way'],
		methods: {
			
			/* 地图初始化*/
			map() {
				var map = new BMap.Map(this.$refs.mapComponent); // 创建Map实例
				window.map = map //将map变量存储在全局

				map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
				if (this.gongneng == 1) {
					map.centerAndZoom(this.loc[1], 15); // 设置地图显示的城市 此项是必须设置的
					this.pilyLine(this.loc[0], this.loc[1], 'red');
					this.pilyLine(this.loc[1], this.loc[2], 'greed');

				}
				if (this.gongneng == 2) {
					map.centerAndZoom(this.loc, 16); // 设置地图显示的城市 此项是必须设置的
					this.addLocMarker();
				}
				if (this.gongneng == 3) {
					map.centerAndZoom('广州', 12);
					this.showAllCarMarker();
				}
				if (this.gongneng == 4) {
					map.centerAndZoom(this.loc, 14);
					this.addLocMarker();

					this.addBusRoute(this.way);
				}

			},
			/* 导航小车动*/
			run() {
				this.lushu.start();
				this.lushu.showInfoWindow();
			},
			addBusRoute(way) {
				let points = [];
				for (let item in way) {
					let point = new BMap.Point(way[item].lon, way[item].lat);
					points.push(point);
					if (item == 0) {
						let marker = new BMap.Marker(point, {
							title: `出发点：${way[item].name}`,
						});
						let content =
							`<div style="z-index:1">
								<p><span style="color:red;font-size:14px">出发地:</span>${way[item].name}</p>
							</div>`;
						let label = new BMap.Label(content, {
							offset: new BMap.Size(20, -10)
						});
						marker.setLabel(label);

						map.addOverlay(marker);
					} else if (item == way.length - 1) {
						let marker = new BMap.Marker(point, {
							title: `目的点：${way[item].name}`,
						});
						map.addOverlay(marker);

						let content =
							`<div >
								<p><span style="color:red;font-size:14px">目的地:</span>${way[item].name}</p>
							</div>`;
						let label = new BMap.Label(content, {
							offset: new BMap.Size(20, -10)
						});
						marker.setLabel(label);
					} else {
						let marker = new BMap.Marker(point, {
							title: `途径点：${way[item].name}`
						});
						map.addOverlay(marker);
					}
				}

				for (let item in points) {
					if (item == 0) {

					} else {

						let h = parseInt(Math.random() * 360)
						let c = `hsl(${h},50%,50%)`;
						this.pilyLine(points[item - 1], points[item], c);

					}
				}
			},
			showAllCarMarker() {
				let geoc = new BMap.Geocoder();
				for (let i in this.cars) {
					let car = this.cars[i]
					let info = car.license_num;
					let point = new BMap.Point(car.cur_loc_lon, car.cur_loc_lat);
					geoc.getLocation(point, (result) => {
						let addComp = result.addressComponents;
						let address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " +
							addComp.streetNumber;
						this.addMarker(point, car, address)
					})
				}
			},
			addLocMarker(loc = this.loc,distance,paytime) {
				let marker = new BMap.Marker(loc, {
					// 指定Marker的icon属性为Symbol
					icon:new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
							anchor: new BMap.Size(27, 13)}),
					title: '当前位置'
				});
				let content =''
				let label = ''
				if(this.gongneng == 1){
					content =
						`<div style="z-index:22">
							<p><span style="color:red;font-size:14px">车辆:</span>${this.info.license_num}</p>
							<p ><span style="color:red;font-size:14px">车辆状态:</span>正在行驶</p>	
							<p><span style="color:red;font-size:14px">车辆类型:</span>${this.info.type}</p>
							
							<p ><span style="color:red;font-size:14px">距离目的地:</span>${distance}</p>
							<p ><span style="color:red;font-size:14px">预计花费时间:</span>${paytime}</p>	
						</div>`;
					label = new BMap.Label(content, {
							offset: new BMap.Size(20, -100)
						});
				}
				else if(this.gongneng ==4){
					content =
						`<div style="z-index:22">
							<p><span style="color:red;font-size:14px">车辆:</span>${this.info.license_num}</p>
							<p><span style="color:red;font-size:14px">车辆类型:</span>${this.info.type}</p>
							<p ><span style="color:red;font-size:14px">现在所在的位置:</span>${this.address}</p>	
						</div>`;
					label = new BMap.Label(content, {
						offset: new BMap.Size(20, -60)
					});	
				}else{
					content =
						`<div style="z-index:22">
							<p><span style="color:red;font-size:14px">车辆:</span>${this.info.license_num}</p>
							<p ><span style="color:red;font-size:14px">现在所在的位置:</span>${this.address}</p>	
						</div>`;
					
					label = new BMap.Label(content, {
						offset: new BMap.Size(20, -50)
					});	
				}
				marker.setLabel(label);
				map.addOverlay(marker);
			},
			addMarker(point, info, address) {
				let marker ='';
				let state = '';
				if(info.state == 0){
					state = '未行驶'
					marker =new BMap.Marker(point);
				}else{
					state = '正在行驶'
					marker =new BMap.Marker(point,{
						// 指定Marker的icon属性为Symbol
						icon:new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
								anchor: new BMap.Size(27, 13)})
					});
				}
				let html =
					`<div >
						<p><span style="color:red;font-size:14px">车辆:</span>${info.license_num}</p>
						<p><span style="color:red;font-size:14px">车辆类型:</span>${info.type}</p>

						<p ><span style="color:red;font-size:14px">车辆状态:</span>${state}</p>	
						<p ><span style="color:red;font-size:14px">现在所在的位置:</span>${address}</p>	
					</div>`;
				let infoWindow = new BMap.InfoWindow(html);
				marker.infoWindow = infoWindow;
				let flag = false;
				marker.addEventListener('click', function(e) {
					if (flag == false) {
						this.openInfoWindow(e.target.infoWindow)
						flag = true;
					} else {
						this.closeInfoWindow(e.target.infoWindow)
						flag = false;
					}
				});
				map.addOverlay(marker);
			},
			pilyLine(l1, l2, color = 'red', weight = 5) { //出发地到现在所在地
				var driving = new BMap.DrivingRoute(map, {
					renderOptions: {
						map: map,
						autoViewport: true
					},
					onPolylinesSet: function(routes) {
						let searchRoute = routes[0].getPolyline(); //导航路线
						map.addOverlay(searchRoute);
					},
					onMarkersSet: function(routes) {
						map.removeOverlay(routes[0].marker); //删除起点
						map.removeOverlay(routes[routes.length - 1].marker); //删除终点
					}
				});
				driving.setSearchCompleteCallback(()=> {
					var plan = driving.getResults().getPlan(0);
					if(this.gongneng == 1 && color != 'red'){
						let distance = plan.getDistance();
						let time = plan.getDistance(false) / 20;
						let paytime = this.payTime(time);
						this.paytime = paytime;
						this.distance = distance
						this.addLocMarker(this.loc[1],distance,paytime);
					}
					for (var i = 0; i < plan.getNumRoutes(); i++) {
						var pts = plan.getRoute(i).getPath();
						//重点在这   这个地方是关于修改颜色的
						var polyline = new BMap.Polyline(pts, {
							strokeColor: color,
							strokeWeight: weight,
							strokeOpacity: 1
						});
						map.addOverlay(polyline);
					}
				})
				driving.search(l1, l2);
			},

			daohang() {
				let chepai = this.carinfo.license_num;
				let speed = this.speed;
				let xian = this.loc[1];
				let mu = this.loc[2]
				let content =
					`	<div style="color:#000;padding:5px 5px;text-align:left">
								<p style="font-size:14px;color:red; "><span style="color:#000;">车牌号:</span>${this.info.license_num}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车辆类型:</span>${this.info.type}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车辆品牌:</span>${this.info.brand}</p>
								<p style="font-size:14px;color:red;"><span style="color:#000;">车速:</span>${this.speed}km/h</p>
								</div>
								`
				// 实例化一个驾车导航用来生成路线
				let drv = new BMap.DrivingRoute("北京", {
					onSearchComplete: (res) => {
						if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
							let plan = res.getPlan(0);
							let arrPois = [];
							for (let j = 0; j < plan.getNumRoutes(); j++) {
								let route = plan.getRoute(j);
								arrPois = arrPois.concat(route.getPath());
							}
							map.addOverlay(new BMap.Polyline(arrPois, {
								strokeColor: "red",
								strokeWeight: 5,
							}));
							map.setViewport(arrPois);

							this.lushu = new BMapLib.LuShu(map, arrPois, {
								defaultContent: content,
								autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
								icon: new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
									anchor: new BMap.Size(27, 13)
								}),
								speed: speed,
								enableRotation: true, //是否设置marker随着道路的走向进行旋转
								landmarkPois: [],
							});
						}
					}
				});
				/*
				现在所在地到目的地
				*/
				drv.search(xian, mu);

				this.chongxie()

			},
			chongxie() {
				var _that = this;
				BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect) {
					var pointsArr = [initPos, targetPos]; //点数组
					var me = this,
						//当前的帧数
						currentCount = 0,
						//步长，米/秒
						timer = 10,
						step = this._opts.speed / (1000 / timer),
						//初始坐标
						init_pos = this._projection.lngLatToPoint(initPos),
						//获取结束点的(x,y)坐标
						target_pos = this._projection.lngLatToPoint(targetPos),
						//总的步长
						count = Math.round(me._getDistance(init_pos, target_pos) / step);

					this._map.addOverlay(new BMap.Polyline(pointsArr, {
						strokeColor: "green",
						strokeWeight: 6,
						strokeOpacity: 0.5
					})); // 画线 

					// 			获取当前的位置
					_that.nowLoction = JSON.stringify(pointsArr[0]);

					//如果小于1直接移动到下一点

					if (count < 1) {
						me._moveNext(++me.i);
						return;
					}
					//两点之间匀速移动
					me._intervalFlag = setInterval(function() {
						//两点之间当前帧数大于总帧数的时候，则说明已经完成移动
						if (currentCount >= count) {
							clearInterval(me._intervalFlag);
							//移动的点已经超过总的长度
							if (me.i > me._path.length) {
								return;
							}
							//运行下一个点
							me._moveNext(++me.i);
						} else {
							currentCount++;
							var x = effect(init_pos.x, target_pos.x, currentCount, count),
								y = effect(init_pos.y, target_pos.y, currentCount, count),
								pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
							//设置marker
							if (currentCount == 1) {
								var proPos = null;
								if (me.i - 1 >= 0) {
									proPos = me._path[me.i - 1];
								}
								if (me._opts.enableRotation == true) {
									me.setRotation(proPos, initPos, targetPos);
								}
								if (me._opts.autoView) {
									if (!me._map.getBounds().containsPoint(pos)) {
										me._map.setCenter(pos);
									}
								}
							}
							//正在移动

							me._marker.setPosition(pos);
							//设置自定义overlay的位置
							me._setInfoWin(pos);

						}
					}, timer);
				}
			},
			postCarLoc(val) { //每当现在位置改变一次就将数据上传至服务器
				let car = {
					id: this.info.id,
					cur_loc_lon: val.lng,
					cur_loc_lat: val.lat
				}
				this.$axios.post('/api/info/updateCarLoc', {
						car: car
					})
					.then(data => {
						if (data.status == 200) {

						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			payTime(val) { // 到达目的地的时间时的格式
				val = parseInt(val)
				if (val <= 60) {
			
					return `${val}秒`
				} else if (val <= 60 * 60) {
					let m = parseInt(val / 60);
					let s = val - m * 60;
					return `${m}分钟${s}秒`
				} else if (val < 24 * 60 * 60) {
					let h = parseInt(val / 3600);
					let m = parseInt(val - 3600 * h);
					let s = val - 3600 * h - m * 60;
					return `${h}小时${m}分钟${s}秒`
				}
			},

		}

	}
</script>

<style lang="less" scoped>
	.map {
		z-index: 11;

		#mapComponent {
			width: 100%;
			height: 270px;
		}
	}
</style>
